package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private TaskService taskService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] Ids = Convert.toLongArray(ids);
        for (Long id : Ids) {
            carPackageAuditMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImgAsStream(Long id) {
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId();//审核对象关联的流程实例Id
        List<String> highLightedActivities = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            //如果处于审核中，需要高亮目前运行节点
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);//根据流程实例Id获取到目前活动节点
        }else{
            //如果处于审核通过，不需要高亮任何节点
            highLightedActivities = new ArrayList<>();
        }
        //根据bpmnInfoId对象查询的bpmnInfo对象,对象中存储流程定义的ID
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmninfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model, highLightedActivities,Collections.EMPTY_LIST,"宋体","宋体","宋体");

    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        //合理化校验
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有处于审核中的记录才可以进行撤销操作");
        }
        //把服务单项的审核状态更新初始化
        Long serviceItemId = audit.getServiceItemId();
        serviceItemService.changeAuditStatus(serviceItemId, ServiceItem.AUDITSTATUS_INIT);
        //把流程实例删除
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程撤销");
        //把审核对象的状态修改已撤销
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("非法操作");
        }
        if (!ShiroUtils.getUserId().equals(audit.getAuditorId())){
            throw new BusinessException("非法操作");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            info = "["+userName+"]同意,审批意见"+info;
        }else{
            info = "["+userName+"]拒绝,审批意见"+info;
        }
        audit.setInfo(audit.getInfo()+"</br>"+info);
        Task currentTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        taskService.complete(currentTask.getId());
        audit.setAuditTime(new Date());
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            Task nextTask = taskService.createTaskQuery().processDefinitionKey(audit.getInstanceId()).singleResult();
            if (nextTask==null){
                audit.setAuditorId(null);
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }else{
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }
        }else{
            audit.setAuditorId(null);
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }

}
